package com.coolwen.service;

import com.alibaba.fastjson.JSON;
import com.coolwen.dao.AddressMapper;
import com.coolwen.dao.CartProductMapper;
import com.coolwen.dao.OrdersMapper;
import com.coolwen.dao.ProductMapper;
import com.coolwen.entity.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by user on 2016/7/29.
 */
@Service("orderService")
public class OrdersServiceImpl implements OrdersService {


    private Logger logger = Logger.getLogger(getClass());
    @Autowired
    private OrdersMapper orderDao;

    @Autowired
    private AddressMapper addressDao;

    @Autowired
    private CartProductMapper cartProductDao;

    @Autowired
    private ProductMapper productDao;

    /**
     * @param orders
     * @param user
     * @param aid    address Id
     * @param cps
     */
    @Override
    public void add(Orders orders, User user, int aid, List<CartProduct> cps) {
        Address a = addressDao.load(aid);
        logger.info("OrdersServiceImpl-------Address------>>>>>>>>>" + JSON.toJSON(a));
        orders.setAddress(a);
        orders.setUser(user);
        logger.info("OrdersServiceImpl-------orders------>>>>>>>>>" + JSON.toJSON(orders));
        orderDao.insertSelective(orders);
        //接着添加购物对象
        for (CartProduct cp : cps) {
            this.addCartProduct(cp, orders, cp.getProduct());
        }
    }

    @Override
    public void delete(int id) {
        this.deleteCartProduct(id);
        Orders o = this.load(id);
        if (o.getStatus() != 1) throw new ShopException("只能删除未付款的订单");
        orderDao.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Orders orders) {
        orderDao.updateByPrimaryKey(orders);
    }

    @Override
    public void updatePrice(int id, double price) {
        Orders o = this.load(id);
        o.setPrice(price);
        orderDao.updateByPrimaryKey(o);
    }

    @Override
    public void updatePayStatus(int id) {
        Orders o = this.load(id);
        List<CartProduct> cps = o.getProducts();
        List<Product> ps = new ArrayList<Product>();
        for (CartProduct cp : cps) {
            int num = cp.getNumber();
            Product p = productDao.load(cp.getProduct().getId());
            if (p.getStock() < num) {
                throw new ShopException("要买的" + p.getName() + "库存不足");
            } else {
                p.setStock(p.getStock() - num);
                ps.add(p);
            }
        }
        //更新库存
        for (Product pp : ps) {
            productDao.update(pp);
            //        productDao.update(pp.getCategory().getId(), pp);
        }
        o.setStatus(2);
        o.setPayDate(new Date());
        orderDao.updateByPrimaryKey(o);
    }

    @Override
    public void updateSendStatus(int id) {
        Orders o = this.load(id);
        o.setStatus(3);
        orderDao.updateByPrimaryKey(o);
    }

    @Override
    public void updateConfirmStatus(int id) {
        Orders o = this.load(id);
        o.setStatus(4);
        o.setConfirmDate(new Date());
        orderDao.updateByPrimaryKey(o);
    }

    @Override
    public Orders load(int id) {
        return orderDao.load(id);
    }

    @Override
    public Pager<Orders> findByUser(int userId, int status) {
        int pageSize = SystemContext.getPageSize();
        int pageOffset = SystemContext.getPageOffset();
        Pager<Orders> pages = new Pager<Orders>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        if (status > 0) {
            params.put("status", status);
        }

        List<Orders> datas = orderDao.find_by_user(params);
        int totalRecord = orderDao.find_by_user_count(params);
        pages.setDatas(datas);
        pages.setPageOffset(pageOffset);
        pages.setPageSize(pageSize);
        pages.setTotalPage(totalRecord);
        return pages;
    }

    @Override
    public Pager<Orders> findByStatus(int status) {
        int pageSize = SystemContext.getPageSize();
        int pageOffset = SystemContext.getPageOffset();
        Pager<Orders> pages = new Pager<Orders>();
        Map<String, Object> params = new HashMap<String, Object>();
        if (status > 0) {
            params.put("status", status);
        }
        List<Orders> datas = orderDao.find_by_user(params);
        int totalRecord = orderDao.find_by_user_count(params);
        pages.setDatas(datas);
        pages.setPageOffset(pageOffset);
        pages.setPageSize(pageSize);
        pages.setTotalPage(totalRecord);
        return pages;
    }

    @Override
    public void addCartProduct(CartProduct cp, Orders o, Product p) {
        cp.setOrders(o);
        cp.setProduct(p);
        //?????????????
        cartProductDao.insert(cp);
    }

    @Override
    public void deleteCartProduct(int oid) {
        cartProductDao.deleteByOrders(oid);
    }
}
